import { Label, sys } from "cc";

class SpeechCtrl {

    private recognition: any = null;;
    isListening: boolean = false;
    public script = "";
    public displayLabel: Label = null;
    public onUpdateCallback: (text: string) => void = null;
    public onEndCallback: (text: string) => void = null;
    public onStartCallback: (text: string) => void = null;

    isPlaying = false;

    init(cb?: (text: string) => void) {
        if ('webkitSpeechRecognition' in window) {
            // 初始化语音识别API
            if (cb) this.onEndCallback = cb;
            this.recognition = new ((window as any).webkitSpeechRecognition)();

            // if(sys.os == sys.OS.ANDROID || sys.os == sys.OS.WINDOWS){
            //     this.recognition = new ((window as any).SpeechRecognition)();
            // }else{
            //     this.recognition = new ((window as any).webkitSpeechRecognition)();
            // }
            if (!this.recognition) {
                return false;
            }
            this.recognition.lang = 'zh-CN'; // 设置为中文
            this.recognition.continuous = true;
            this.recognition.interimResults = true; // 只返回最终结果

            // 事件处理
            this.recognition.onstart = () => {
                console.log('语音识别已启动，请开始说话。');
                this.isListening = true;
                this.script = '';
            };

            this.recognition.onresult = (event: any) => {
                let finalTranscript = ''; // 最终的转录文本
                let interimTranscript = ''; // 临时的转录文本
                let final = false;
                for (let i = event.resultIndex; i < event.results.length; ++i) {
                    if (event.results[i].isFinal) {
                        finalTranscript += event.results[i][0].transcript;
                        final = true;
                    } else {
                        interimTranscript += event.results[i][0].transcript;
                    }
                }
                if (this.onStartCallback) this.onStartCallback(interimTranscript);

                if (final) {
                    this.script = finalTranscript;
                    // if (finalTranscript.length > 0) {
                    //     if (this.onEndCallback) this.onEndCallback(this.script);
                    // }
                } else {
                    this.script = interimTranscript;
                }
                if (this.displayLabel) {
                    this.displayLabel.string = this.script;
                };
                // if(this.onUpdateCallback)this.onUpdateCallback(this.script);

            };

            this.recognition.onerror = (event) => {
                // console.error('语音识别错误:', event.error);
                if (event.error === 'no-speech') {
                    console.log('未检测到语音，准备重启语音识别...');
                    setTimeout(() => {
                        // 检查是否正在播放音频
                        if (!this.isPlaying) {
                            // 不在播放音频时，重启语音识别
                            this.recognition.start();
                        } else {
                            // 正在播放音频时，不做任何操作（或者可以在这里进行一些其他的状态更新）
                            console.log('因为正在播放音频，所以不重新启动语音识别。');
                        }
                    }, 50);

                }
            };

            this.recognition.onend = () => {
                console.log('语音识别已结束。');
                if (this.onEndCallback) this.onEndCallback(this.script);

                if (this.displayLabel) {
                    this.displayLabel.string = this.script;
                };
                this.onEndCallback = null;
                // this.recognition.start();
                this.isListening = false;
            };
            return true;

        } else {
            console.error('此浏览器不支持 Web Speech API。');
            return false;

        }
    }
    setPlaying(isPlaying) {
        this.isPlaying = isPlaying;
        // 如果正在播放，则停止语音识别
        if (isPlaying && this.isListening) {
            this.recognition.stop();
        }
        // 如果不是在播放状态，并且语音识别当前不是在监听状态，则开始语音识别
        if (!isPlaying && !this.isListening) {
            this.recognition.start();
        }
    }

    checkPermission() {

    }

    public startRecord(): void {
        if (this.recognition && !this.isListening) {
            const self = this;
            this.recognition.stop();

            try {
                self.recognition.start();
            } catch (error) {
                console.error("rego error:", error);
            }
        }
    }

    public endRecord(): void {
        if (this.recognition && this.isListening) {
            this.isListening = false;
            this.recognition.stop();
        } else {
            console.log('语音识别未启动。');
        }
    }

    public checkBrowserSupport(): boolean {
        return 'webkitSpeechRecognition' in window;
    }
}

const speech = new SpeechCtrl;

export default speech;




